#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2005-2010 TUBITAK/UEKAE
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# Please read the COPYING file.

import sys
import optparse

import scom
import sorg
from sorg.consts import package_sep
from sorg.utils import *

sorg_info = " Xorg AutoConfiguration tool"

link = scom.Link()

def safe():
    if link.Xorg.Display["sorg"].safeConfig():
        link.Xorg.Display["sorg"].syncConfigs()
        print("Initialized a safe configuration using VESA driver.")
    else:
        print("Failed to create a safe configuration with VESA driver.")

def probe(opts):
    if link.Xorg.Display["sorg"].initialConfig():
        link.Xorg.Display["sorg"].syncConfigs()
        print("Created an initial configuration for your video device.")
    else:
        print("An error occured while creating an initial configuration.")

def setDriver(driver):
    # Needed for compatibility with old sorg versions
    oldnames = {
            "fglrx/ati-drivers":            "fglrx",
            "nvidia/xorg-video-nvidia96":   "nvidia96",
            "nvidia/xorg-video-nvidia173":  "nvidia173",
            "nvidia/xorg-video-nvidia185":  "nvidia185",
            }
    if driver in oldnames:
        driver = oldnames[driver]

    if package_sep in driver:
        drv, pkg = driver.split(package_sep, 1)
        if pkg.replace("-", "_") not in list(link.Xorg.Driver):
            print("Package is not installed: %s" % pkg)
            sys.exit(1)

    link.Xorg.Display["sorg"].setDriver(driver)
    link.Xorg.Display["sorg"].syncConfigs()

    if driver:
        print("The video driver is set to '%s'." % driver)
    else:
        print("The video driver will be selected by the X server.")


if __name__ == "__main__":
    parser = optparse.OptionParser(description = "%s version %s"
                                    % (sorg_info, sorg.versionString()))

    parser.add_option("-s", "--safe", action="store_true",
        dest="safe", default=False,
        help="setup VESA config without probing hardware")

    parser.add_option("-p", "--probe", action="store_true",
        dest="probe", default=False,
        help="force probing all devices, even if xorg.conf exists")

    parser.add_option("-d", "--driver", action="store", type="string",
        dest="driver", default=None, metavar="DRIVER[%sPACKAGE]" % package_sep,
        help="set video card driver to DRIVER")

    parser.add_option("-k", "--keymap", action="store", type="string",
        dest="keymap", default=None, metavar="LAYOUT[/VARIANT]",
        help="changes keyboard map")

    opts, args = parser.parse_args()

    if opts.safe:
        safe()

    elif opts.probe:
        probe(opts)

    elif opts.driver is not None:
        setDriver(opts.driver)

    elif opts.keymap:
        if "/" in opts.keymap:
            layout, variant = opts.keymap.split("/", 1)
        else:
            layout, variant = opts.keymap, ""

        link.Xorg.Display["sorg"].setKeymap(layout, variant)

    else:
        parser.print_help()
